<template>
  <div v-if="menu">
    <el-menu
      :popper-append-to-body="false"
      :default-active="menu.children[0].code"
      class="el-menu-vertical-demo"
      mode="horizontal"
      background-color="#545c64"
      text-color="#fff"
      active-text-color="#ffd04b"
      @select="handleSelect"
    >
      <MenuItem :menu="menuItem" :key="menuItem.code" v-for="menuItem in menu.children" />
    </el-menu>
  </div>
</template>
<script>
import MenuItem from '@/components/menu/MenuItem'
import menuService from '../../api/MenuService'
import cacheManage from '../../cache/CacheManage'
import { ref, onMounted } from 'vue'
export default {
  name: 'SysMenu',
  mixins: [],
  components: { MenuItem },

  setup () {
    const menu = ref(null)
    onMounted(async () => {
      const commonInfo = cacheManage.getDefaultCommonInfo()
      const menuMessage = await menuService.getRootMenu(commonInfo)
      if (!menuMessage.success) { return }
      menu.value = menuMessage.value
    })

    function getMenuByCode (thatMenu, code) {
      if (thatMenu.code === code) return thatMenu
      for (let i = 0; i < thatMenu.children.length; i++) {
        const childMenu = getMenuByCode(thatMenu.children[i], code)
        if (childMenu != null) return childMenu
      }
      return null
    }

    return {
      menu,
      getMenuByCode
    }
  },
  methods: {
    handleSelect (index, indexPath) {
      const selectedMenu = this.getMenuByCode(this.menu, index)
      if (selectedMenu != null) {
        this.$emit('menuClick', selectedMenu)
      }
    }
  }
}

</script>

<style lang="scss" scope>
</style>
